use crate::session::SessionManager;
use leptos::prelude::*;
use leptos_router::hooks::use_location;

#[derive(Debug, Clone, PartialEq)]
pub struct MenuItem {
    pub id: String,
    pub label: String,
    pub icon: String,
    pub path: Option<String>,            // 一级菜单可能没有路径
    pub children: Option<Vec<MenuItem>>, // 子菜单项
}

/// Menu Component
/// Displays navigation menu for the management pages with support for nested menus
#[component]
#[must_use]
pub fn UiMenu(#[prop(optional)] class: Option<String>) -> impl IntoView {
    // 初始化菜单状态，首先尝试从会话存储加载，如果没有则使用空集合
    let initial_expanded = SessionManager::load_expanded_menus();
    let (expanded_menus, set_expanded_menus) = signal(initial_expanded);
    let (active_item, set_active_item) = signal(String::new());
    let location = use_location();

    // 根据当前路径设置活动项和展开菜单
    Effect::new(move |_| {
        let path = location.pathname.get();
        let (menu_id, item_id) = match path.as_str() {
            "/apps/list" | "/apps/publish" | "/apps/settings" => {
                (Some("apps"), Some(path.trim_start_matches("/apps/")))
            }
            "/tenants/list" | "/tenants/apps" => {
                (Some("tenants"), Some(path.trim_start_matches("/tenants/")))
            }
            "/accounts/list" | "/accounts/roles" => (
                Some("accounts"),
                Some(path.trim_start_matches("/accounts/")),
            ),
            _ => (None, None),
        };

        // 确保当前路径对应的菜单是展开的，但保留用户手动展开的其他菜单
        if let Some(menu_id) = menu_id {
            set_expanded_menus.update(|set| {
                set.insert(menu_id.to_string());
                // 同步更新到会话存储
                SessionManager::save_expanded_menus(set);
            });
        }

        if let Some(item_id) = item_id {
            set_active_item.set(format!("{}-{}", menu_id.unwrap_or(""), item_id));
        }
    });

    let toggle_menu = move |menu_id: String| {
        set_expanded_menus.update(|set| {
            if set.contains(&menu_id) {
                set.remove(&menu_id);
            } else {
                set.insert(menu_id);
            }
            // 同步更新到会话存储
            SessionManager::save_expanded_menus(set);
        });
    };

    let base = "p-1";
    let class = class.map_or_else(|| base.to_string(), |c| format!("{base} {c}"));

    view! {
        <div class=class>
            <nav>
                <ul class="space-y-1">
                    // 应用管理菜单
                    <li class="pl-2">
                        <div
                            class="flex items-center justify-between p-1.5 text-sm font-normal rounded-md transition duration-200 cursor-pointer text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700"
                            on:click=move |_| toggle_menu("apps".to_string())
                        >
                            <div class="flex items-center">
                                <span class="text-sm">"应用管理"</span>
                            </div>
                            <span class="text-xs">
                                {if expanded_menus.get().contains("apps") { "▼" } else { "▶" }}
                            </span>
                        </div>
                        <Show when=move || expanded_menus.get().contains("apps")>
                            <ul class="py-1 space-y-1">
                                <li class="pl-6">
                                    <a
                                        class=move || {
                                            let base_classes = "flex items-center p-1.5 text-sm font-normal rounded-md transition duration-200";
                                            if active_item.get() == "apps-list" {
                                                format!("{base_classes} bg-blue-500/20 text-white")
                                            } else {
                                                format!("{base_classes} text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700")
                                            }
                                        }
                                        href="/apps/list"
                                        on:click=move |_| set_active_item.set("apps-list".to_string())
                                    >
                                        <span class="text-sm">"应用上架"</span>
                                    </a>
                                </li>
                                <li class="pl-6">
                                    <a
                                        class=move || {
                                            let base_classes = "flex items-center p-1.5 text-sm font-normal rounded-md transition duration-200";
                                            if active_item.get() == "apps-publish" {
                                                format!("{base_classes} bg-blue-500/20 text-white")
                                            } else {
                                                format!("{base_classes} text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700")
                                            }
                                        }
                                        href="/apps/publish"
                                        on:click=move |_| set_active_item.set("apps-publish".to_string())
                                    >
                                        <span class="text-sm">"应用发布"</span>
                                    </a>
                                </li>
                                <li class="pl-6">
                                    <a
                                        class=move || {
                                            let base_classes = "flex items-center p-1.5 text-sm font-normal rounded-md transition duration-200";
                                            if active_item.get() == "apps-settings" {
                                                format!("{base_classes} bg-blue-500/20 text-white")
                                            } else {
                                                format!("{base_classes} text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700")
                                            }
                                        }
                                        href="/apps/settings"
                                        on:click=move |_| set_active_item.set("apps-settings".to_string())
                                    >
                                        <span class="text-sm">"应用设置"</span>
                                    </a>
                                </li>
                            </ul>
                        </Show>
                    </li>

                    // 租户管理菜单
                    <li class="pl-2">
                        <div
                            class="flex items-center justify-between p-1.5 text-sm font-normal rounded-md transition duration-200 cursor-pointer text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700"
                            on:click=move |_| toggle_menu("tenants".to_string())
                        >
                            <div class="flex items-center">
                                <span class="text-sm">"租户管理"</span>
                            </div>
                            <span class="text-xs">
                                {if expanded_menus.get().contains("tenants") { "▼" } else { "▶" }}
                            </span>
                        </div>
                        <Show when=move || expanded_menus.get().contains("tenants")>
                            <ul class="py-1 space-y-1">
                                <li class="pl-6">
                                    <a
                                        class=move || {
                                            let base_classes = "flex items-center p-1.5 text-sm font-normal rounded-md transition duration-200";
                                            if active_item.get() == "tenants-list" {
                                                format!("{base_classes} bg-blue-500/20 text-white")
                                            } else {
                                                format!("{base_classes} text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700")
                                            }
                                        }
                                        href="/tenants/list"
                                        on:click=move |_| set_active_item.set("tenants-list".to_string())
                                    >
                                        <span class="text-sm">"租户信息"</span>
                                    </a>
                                </li>
                                <li class="pl-6">
                                    <a
                                        class=move || {
                                            let base_classes = "flex items-center p-1.5 text-sm font-normal rounded-md transition duration-200";
                                            if active_item.get() == "tenants-apps" {
                                                format!("{base_classes} bg-blue-500/20 text-white")
                                            } else {
                                                format!("{base_classes} text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700")
                                            }
                                        }
                                        href="/tenants/apps"
                                        on:click=move |_| set_active_item.set("tenants-apps".to_string())
                                    >
                                        <span class="text-sm">"租户应用"</span>
                                    </a>
                                </li>
                            </ul>
                        </Show>
                    </li>

                    // 账号管理菜单
                    <li class="pl-2">
                        <div
                            class="flex items-center justify-between p-1.5 text-sm font-normal rounded-md transition duration-200 cursor-pointer text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700"
                            on:click=move |_| toggle_menu("accounts".to_string())
                        >
                            <div class="flex items-center">
                                <span class="text-sm">"账号管理"</span>
                            </div>
                            <span class="text-xs">
                                {if expanded_menus.get().contains("accounts") { "▼" } else { "▶" }}
                            </span>
                        </div>
                        <Show when=move || expanded_menus.get().contains("accounts")>
                            <ul class="py-1 space-y-1">
                                <li class="pl-6">
                                    <a
                                        class=move || {
                                            let base_classes = "flex items-center p-1.5 text-sm font-normal rounded-md transition duration-200";
                                            if active_item.get() == "accounts-list" {
                                                format!("{base_classes} bg-blue-500/20 text-white")
                                            } else {
                                                format!("{base_classes} text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700")
                                            }
                                        }
                                        href="/accounts/list"
                                        on:click=move |_| set_active_item.set("accounts-list".to_string())
                                    >
                                        <span class="text-sm">"账号设置"</span>
                                    </a>
                                </li>
                                <li class="pl-6">
                                    <a
                                        class=move || {
                                            let base_classes = "flex items-center p-1.5 text-sm font-normal rounded-md transition duration-200";
                                            if active_item.get() == "accounts-roles" {
                                                format!("{base_classes} bg-blue-500/20 text-white")
                                            } else {
                                                format!("{base_classes} text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700")
                                            }
                                        }
                                        href="/accounts/roles"
                                        on:click=move |_| set_active_item.set("accounts-roles".to_string())
                                    >
                                        <span class="text-sm">"角色管理"</span>
                                    </a>
                                </li>
                            </ul>
                        </Show>
                    </li>
                </ul>
            </nav>
        </div>
    }
}
